import cv2
import requests
import numpy as np
import time


lineColor = (0,0,255)

class cv2Stream():  
    def __init__(self,pqueue,imgurl,imgpth,mFunc,kFunc,cimgFunc):  
        self.queue = pqueue      #返回动作事件的列队
        self.mouseFunc = mFunc
        self.keyFunc = kFunc
        self.imgChangeFunc = cimgFunc
        self.pth = imgpth
        self.url = imgurl
        self.winname = 'fengmm521.taobao.com'
        cv2.namedWindow(self.winname)
        cv2.setMouseCallback(self.winname, self.on_EVENT_LBUTTONDOWN)
        self.img = None
        self.imgSize = None
        self.initCV2()
    def initCV2(self):
        self.img = cv2.imread(self.pth)
        self.imgSize = (self.img.shape[1],self.img.shape[0])
        self.onImgSizeChange()
    def on_EVENT_LBUTTONDOWN(self,event, x, y,flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            # eobj = _eventObj(1,(x,y))
            # self.queue.put(eobj)
            self.mouseFunc(x,y)
    def on_EVENT_KeyDown(self,pkey):
        # eobj = _eventObj(2,pkey)
        # self.queue.put(eobj)
        self.keyFunc(pkey)
    def onImgSizeChange(self):
        self.imgChangeFunc(self.imgSize)
    def start(self):
        r = requests.get(self.url,stream=True)
        if(r.status_code == 200):
            bt = bytes()
            for chunk in r.iter_content(chunk_size=58566): #58566
                bt += chunk
                a = bt.find(b'\xff\xd8')
                b = bt.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bt[a:b+2]
                    bt = bt[b+2:]
                    self.img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    if self.imgSize[0] != self.img.shape[1] or self.imgSize[1] != self.img.shape[0]:
                        self.imgSize = (self.img.shape[1],self.img.shape[0])
                        self.onImgSizeChange()
                    ptstart = (0,int(self.imgSize[1]/2))
                    ptend = (self.imgSize[0],int(self.imgSize[1]/2))
                    cv2.line(self.img,ptstart,ptend,lineColor,1,4)
                    ptstart = (int(self.imgSize[0]/2),0)
                    ptend = (int(self.imgSize[0]/2),int(self.imgSize[1]))
                    cv2.line(self.img,ptstart,ptend,lineColor,1,4)
                    cv2.imshow(self.winname, self.img)
                    key = cv2.waitKey(1)
                    if key > 0:
                        self.on_EVENT_KeyDown(key)
        else:
            print("Received unexpected status code {}".format(r.status_code))
        

def main():
    def mouseFunc(p):
        print(p)
    def keyFunc(k):
        print('key down:%d'%(k))
        if theKey & 0xFF == 0x1B:#如果是ESC键接下,则退出
            exit(0)
    while True:
        time.sleep(0.01)

if __name__ == '__main__':  
    main()
    